/*
* Author:JacksonCoder
* CreateTime:
* Version: 1.0.0
*/

#[allow(dead_code)]
struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}

#[derive(Debug)] // 启用调试打印
struct Rectangle {
    width: u32,
    height: u32,
}

// 方法语法（Method Syntax）
/**
定义方法： 使用 impl StructName { } 块。&self 表示不可变借用。
*/
impl Rectangle {
    fn area(&self) -> u32 {
        self.height * self.width
    }
}

// 可变性和额外参数
#[allow(dead_code)]
impl Rectangle {
    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
}

// 关联函数（Associated Functions）
impl Rectangle {
    fn square(size: u32) -> Self {
        Self {
            width: size,
            height: size,
        }
    }
}

fn main() {
    // 元组结构体
    #[allow(dead_code)]
    struct Color(i32, i32, i32);
    let black = Color(0, 0, 0);
    println!("R: {}", black.0);

    // 单元结构体
    struct AlwaysEqual;
    let _subject = AlwaysEqual;
    // println!("subject = {}", subject);

    // 结构体实例化
    let user1 = User {
        active: true,
        username: "alex".to_string(),
        email: "1657816513@163.com".to_string(),
        sign_in_count: 1,
    };
    println!("结构体 user1.email = {}", user1.email);

    let user2 = build_user("24981651@gmail.com".to_string(), "jack".to_string(), 2);
    println!("结构体 user2.email = {}", user2.email);

    // 结构体更新   .. 从另外一个实例复制剩余字段
    let _user3 = User {
        email: String::from("oixjcvan@gmail.com"),
        ..user1
    };

    // 访问和更新字段
    let mut user4 = User {
        active: true,
        username: "alex".to_string(),
        email: "1657816513@163.com".to_string(),
        sign_in_count: 4,
    };
    user4.email = String::from("8420184@qq.com");

    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };
    println!("rect1 是 {:?}", rect1); // 使用 {:?} 打印调试信息

    // 更新字段和调试：使用 dbg! 宏调试表达式值
    let scale = 2;
    let rect2 = Rectangle {
        width: dbg!(30 * scale), // 打印并赋值 60
        height: 50,
    };
    dbg!(&rect2); //调试引用，避免移动所有权

    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };
    println!("面积: {} 平方像素", area(&rect1));

    let rect3 = Rectangle {
        width: 30,
        height: 50,
    };
    println!("面积： {}", rect3.area()); // 调用方法

    let sq = Rectangle::square(324);
    // println!("sq 的值: {}", sq);  编译不过  Rectangle` cannot be formatted with the default formatter
    println!("sq.width 的值: {}", sq.width);
    println!("sq.height 的值: {}", sq.height);
}

// 借用处理：函数借用结构体以避免所有权转移。
fn area(rectangle: &Rectangle) -> u32 {
    rectangle.width * rectangle.height
}

// 字段初始化简写
fn build_user(email: String, username: String, sign_in_count: u64) -> User {
    User {
        active: true,
        username,
        email,
        sign_in_count,
    }
}
